#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class InetAddress
{
public:
    InetAddress(const struct sockaddr_in& addr) : _addr(addr)
    {
        _port = ntohs(_addr.sin_port); //网络序列转主机序列
        // _ip = inet_ntoa(_addr.sin_addr);
        char buffer[64]; //缓冲区由库内维护变为手动维护，避免线程安全问题
        inet_ntop(AF_INET, &addr.sin_addr, buffer, sizeof(buffer));
        _ip = buffer;
    }

    std::string getIp()
    {
        return _ip;
    }

    uint16_t getPort()
    {
        return _port;
    }

    std::string getAddressInfo()
    {
        return "[" + _ip + ":" + std::to_string(_port) + "]";
    }

    struct sockaddr_in& getAddress()
    {
        return _addr;
    }
    
    bool operator==(InetAddress& address)
    {
        return this->_port == address._port;
    }

    ~InetAddress()
    {}
private:
    std::string _ip;
    uint16_t _port;
    struct sockaddr_in _addr;
};